﻿using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace Tools
{
    /// <summary>
    /// URL工具类
    /// </summary>
    public class UrlHelper
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public UrlHelper(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 判断当前请求是否来自移动端浏览器
        /// </summary>
        public bool IsMobileBrowser()
        {
            var context = _httpContextAccessor.HttpContext;
            if (context == null)
                return false;

            var userAgent = context.Request.Headers["User-Agent"].ToString().ToLower();

            if (string.IsNullOrEmpty(userAgent))
                return false;

            // 常见移动端关键字
            string[] mobileKeywords = new[]
            {
                "android", "iphone", "ipad", "ipod", "windows phone", "blackberry",
                "opera mini", "opera mobi", "iemobile", "mobile", "tablet"
            };

            return mobileKeywords.Any(keyword => userAgent.Contains(keyword));
        }

        /// <summary>
        /// 解析URL，返回根域名（以 http://xxx.com 形式）
        /// 例如 /param/? 返回 "/"
        /// </summary>
        public string ParseDomain(string url)
        {
            if (string.IsNullOrEmpty(url))
                return "/";

            if (url.StartsWith("/"))
                return "/";

            try
            {
                Uri uri = new Uri(url);
                return $"{uri.Scheme}://{uri.Authority}";
            }
            catch
            {
                return "/";
            }
        }

        /// <summary>
        /// 修复URL，避免多余的 //
        /// </summary>
        public string FormatUrl(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
                return string.Empty;

            // 拆分协议
            string protocol = "";
            if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
            {
                protocol = "http://";
                url = url.Substring(7);
            }
            else if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            {
                protocol = "https://";
                url = url.Substring(8);
            }

            // 去重路径中的连续 "/"
            // 注意不要误处理 query string 中的内容
            int queryIndex = url.IndexOf('?');
            string path = queryIndex >= 0 ? url.Substring(0, queryIndex) : url;
            string query = queryIndex >= 0 ? url.Substring(queryIndex) : "";

            while (path.Contains("//"))
            {
                path = path.Replace("//", "/");
            }

            return protocol + path + query;
        }

        /// <summary>
        /// 获取URL的上一级目录
        /// </summary>
        public string ParentDir(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
                return "/";

            // 尝试解析为 Uri
            if (Uri.TryCreate(url, UriKind.Absolute, out Uri absoluteUri))
            {
                string path = absoluteUri.AbsolutePath.TrimEnd('/');
                int lastSlashIndex = path.LastIndexOf('/');
                if (lastSlashIndex <= 0)
                    return absoluteUri.GetLeftPart(UriPartial.Authority) + "/";
                string parentPath = path.Substring(0, lastSlashIndex + 1);
                return absoluteUri.GetLeftPart(UriPartial.Authority) + parentPath;
            }

            // 处理相对路径
            string relative = url.TrimEnd('/');
            int slashIndex = relative.LastIndexOf('/');
            if (slashIndex <= 0)
                return "/";

            return relative.Substring(0, slashIndex + 1);
        }



        /// <summary>
        /// 获取当前请求网站的根URL
        /// </summary>
        public string GetRootURL()
        {
            var context = _httpContextAccessor.HttpContext;
            if (context == null)
                return string.Empty;

            var request = context.Request;

            var rootUrl = $"{request.Scheme}://{request.Host}{request.PathBase}";

            return rootUrl;
        }
    }
}
